<?php

/*
    Open Designs Content Management System (odCMS)
    Copyright (C) 2010  Thomas Wong - tom@ztml.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

class localFunctions

{

	/*---------------------------\
	| initialize local functions |
	\---------------------------*/
	function localFunctions()
	{
		if($_REQUEST['delete_member'])
		{
			$this->deleteMember($_REQUEST['delete_member']);
			exit;
		}
		switch($this->_CC_['Page'])
		{
			case '_menus_':
			case '_sections_':
			case '_profile_':
			case '_invite_':
			case '_users_':
			case '_templates_':
			case '_cpanel_':	 $this->_CC_['theme'] = "cpanel";
						 return;
						 
			case '_members_':	 $this->_CC_['theme'] = "odcms_2";
						 return;
						 
			case '_upgrade_':
			case '_sitemap_':
			case 'login':
			case '_designer_':
			case 'OST':
			case '_designs_':	 $this->_CC_['theme'] = "signup";
						 return;
		}
		
		if($_REQUEST['set'] == "register") $this->createAccount($_REQUEST['invite']);
	}
	
	/*---------------\
        | update profile |
        \---------------*/
	function controlPanel()
	{
		$this->_CC_['content'] = $this->getTplMsg("odcms_cpanel");
	}
		
        /*-------------\
        | update menus |
        \-------------*/
	function updateMenus()
	{
		$this->_CC_['content'] = $this->getTplMsg("cpanel_menus");
	}
	
	/*---------------\
        | update profile |
        \---------------*/
	function updateProfile()
	{
		$this->_CC_['content'] = $this->getMemberProfile("update_profile");
	}

	/*-------------\
        | manage users |
        \-------------*/
	function manageUsers()
	{
		$this->_CC_['content'] = $this->getTplMsg("cpanel_users");
	}
	
	/*-----------------\
        | manage templates |
        \-----------------*/
	function manageTemplates()
	{
		$this->_CC_['content'] = $this->getTplMsg("cpanel_templates");
	}
	
	/*-----------------------\
	| process create account |
	\-----------------------*/
	function createAccount($invite)
	{
		//if(!$_SESSION['UserName']) return;
	
		$this->_CC_['Page'] = "_CC_"; // do not get page content
		$this->_CC_['theme'] = "signup";
		
		$this->_CC_['zipcode'] = $_REQUEST['zipcode'];
		$this->_CC_['zip4']    = $_REQUEST['zip4'];
		$this->_CC_['fname']   = $_REQUEST['fname'];
		$this->_CC_['lname']   = $_REQUEST['lname'];
		$this->_CC_['city']    = $_REQUEST['city'];
		$this->_CC_['state']   = $_REQUEST['state'];
		$this->_CC_['profile'] = $_REQUEST['profile'];
		$this->_CC_['password']= $_REQUEST['password'];
		$this->_CC_['cname']   = $_REQUEST['cname'];
		$this->_CC_['ctitle']  = $_REQUEST['ctitle'];
		$this->_CC_['slogan']  = $_REQUEST['slogan'];
		$this->_CC_['uname']   = $_REQUEST['uname'];
		$uname   = preg_replace("/[^a-zA-Z0-9]+/", "", $_REQUEST['uname']);
		
		if(!$this->_CC_['city'] && !$this->_CC_['state'])
		{
			$this->ZIPS = new SQLiteDatabase("../zips.dbf"); // zipcodes database
			$q = $this->ZIPS->query("SELECT City,State FROM zipcodes WHERE zipcode='".$this->_CC_['zipcode']."'");
			list($this->_CC_['city'],$this->_CC_['state']) = $q->fetch();
		}
		$email = $this->_CC_['email'] = $_REQUEST['email'];
		$ip    = $_SERVER['REMOTE_ADDR'];
		if($email)
		{
			if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
			{
				$this->_CC_['content'] .= "<p><font size='4' color='red'>Invalid EMail</font> ($email)</p>";
				$this->_CC_['email'] = "";
				$this->_CC_['content'] .= $this->getTplMsg("signup_username");
				return 1;
			}
		        elseif($ip != "68.192.68.38")
			{
				$q = $this->MEMBERS->query("SELECT ID,eMail,Website FROM members WHERE eMail='$email' or Website='$ip'");
				list($id,$em,$ws) = $q->fetch();

				if($ip==$ws)
				{
					$this->_CC_['content'] .= "<p><font size='4' color='red'>".
						"A site was already created under <a href='?usite=_$id'>your account</a>.</font></p>".
						"<p><a href='http://odcms.net/?Page=Contact Us'>Contact Us</a> if this was created in error.</p>";
					return 1;
				}
				if($em)
				{
					
					$this->_CC_['content'] .= "<p><font size='4' color='red'>EMail ($email) is already used by another member.</font></p>";
					$this->_CC_['email'] = "";
					$this->_CC_['content'] .= $this->getTplMsg("signup_username");
					return 1;
				}
			}
		}
		if(!$uname)
		{
			$this->_CC_['content'] .= $this->getTplMsg("signup_username");
			return;
		}
		if (is_dir("../_$uname"  ))
		{
			$this->_CC_['content'] .= $this->getTplMsg("signup_username_error");
			return;
		}

		$this->_CC_['content'] .= $this->getTplMsg("signup_profile_top");

		if(!$this->createUserSite($uname,$_REQUEST['zipcode'],$_REQUEST['zip4'],0,
					  $this->_CC_['city'],$this->_CC_['state'],$this->_CC_['email'],$ip))
		{
			return;
		}

		$this->_CC_['content'] .= $this->getTplMsg("signup_profile_bottom");
		
		return;
	}

	/*--------------------------\
        | create new user databases |
        \--------------------------*/
	function createUserSite($uname,$zip,$zip4,$dist,$city,$state,$email,$ip)
	{
		$fname = $_REQUEST['fname'];
		$lname = $_REQUEST['lname'];
		$pword = $_REQUEST['password'];
		if(!$uname || !$fname || !$lname || !$pword)
		{
			$this->_CC_['content'] .= "<p><font size='4'>Please enter all the required data:</font></p>";
			return 1;
		}
		
		$this->_CC_['uname'] = $this->username = $uname;
		$this->makeDirectory("../_$uname");
		$this->makeDirectory("../_$uname/users");
		$this->makeDirectory("../_$uname/users/admin");
		$this->makeDirectory("../_$uname/users/admin/images");
		
		$email    = $_REQUEST['email'];
		$title    = $_REQUEST['title'];
		$profile  = $_REQUEST['profile'];
		$cname    = $_REQUEST['cname'];
		$slogan   = $_REQUEST['slogan'];
		$password = crypt($pword,"admin");
		$datetime = $this->_CC_['datetime'];
		if($zip4) $zip = "$zip-$zip4";

		$this->MEMBERS->query("INSERT INTO members VALUES('$uname','$email','$fname $lname','$zip','$dist','$city','$state','$cname','$profile',".
				      "'0','$points','0','0','$credits','0','$climit','$datetime','$datetime','$ip','0','0','0')");
		
		$this->UDB = new SQLiteDatabase("../_$uname/users/admin/contents.dbf"); // user content database
		
		$this->createDbase("menu","menu1");
		$this->UDB->query("INSERT INTO menu1 VALUES('Home','1','menu1^','Document','','','Home Page','','','','$datetime')");
		
		$this->createDbase("document","Document");
		$content  = sqlite_escape_string($this->getTplValue("msgs","new_member_home_page"));
		$this->UDB->query("INSERT INTO Document VALUES('Home','1','Document','Home',".
				  "'$content','$datetime')");

		$this->UDB->query("INSERT INTO Document VALUES('attachment.1','2','Attachment','Section 0','Please update the content...','$datetime')");
		$this->UDB->query("INSERT INTO Document VALUES('attachment.2','3','Attachment','Section 1','Please update the content...','$datetime')");
		$this->UDB->query("INSERT INTO Document VALUES('attachment.3','4','Attachment','Section 2','Please update the content...','$datetime')");
		$this->UDB->query("INSERT INTO Document VALUES('attachment.4','5','Attachment','Section 3','Please update the content...','$datetime')");
		$this->UDB->query("INSERT INTO Document VALUES('attachment.5','6','Attachment','Section 4','Please update the content...','$datetime')");
		
		$profile  = sqlite_escape_string(stripslashes($profile));
		$cname    = sqlite_escape_string(stripslashes($cname));
		$company  = sqlite_escape_string(stripslashes($company));

		$this->MEMBERS = new SQLiteDatabase("../_$uname/members.dbf"); // members database
		$this->createDbase("member","members");

		$q = $this->MEMBERS->query("SELECT Points,Credits FROM points WHERE Action='Signup'");
		list($points,$credits) = $q->fetch();
		
		$q = $this->MEMBERS->query("SELECT Credits FROM points WHERE Action='cLimit'");
		list($climit) = $q->fetch();

		$this->MEMBERS->query("INSERT INTO members VALUES('admin','$email','$fname $lname','$zip','$dist','$city','$state','$cname','$profile',".
				      "'0','$points','0','0','$credits','0','$climit','$datetime','$datetime','','0','0','0')");
		
		$this->createDbase("profile","_profile_");
		$this->UDB->query("INSERT INTO _profile_ VALUES('admin','$zip','$dist','$state','$city','$fname','$lname',".
				      "'$profile','$password','$email','$cname','$title','$slogan',".
				      "'&copy; $fname $lname','smarkup.edt','None','default','$datetime','$datetime')");

		$path = "../_$uname/users/admin/images/";

		if($_FILES['logo']['tmp_name'])
		{
			$this->resizeImage($_FILES['logo']['tmp_name'],0,$path."full",$path."thumb",1);
		}
		else
		{
			$img = @file_get_contents("../templates/img/nophoto.gif");
			$fp = fopen($path."thumb.jpg","w");
			fwrite($fp, $img);
		}
		$index = @file_get_contents("../codes/index");
		$fp = fopen("../_$uname/index.php","w");
		fwrite($fp, $index);
		
		echo "The site ($uname) is sucessfully created. Please use your password and login as admin to update the site's content.".
				"<br /><br />Click <a href='?usite=_$uname&Page=login'>here</a> to sign on";
		exit;
	}
	
        /*-----------------------\
        | display table contents |
        \-----------------------*/
	function dispTable($pname)
	{
		if($this->_CC_['d_table']) $pname = $this->_CC_['d_table'];
		$tpl   = $this->_CC_['t_tpl'];
		if(!$tpl) $tpl = $this->_CC_['ptitle'];
		
		list($header,$fmt,$footer,$form,$update,$delete,$where,$order,$table,$links) = explode("^^^",$this->getTplValue("msgs",$tpl));
		if(!$fmt)
			list($header,$fmt,$footer,$form,$update,$delete,$where,$order,$table,$links) = explode("^^^",$this->getTplValue("msgs","table_content"));

		$table = trim($table); $links = trim($links); $update = trim($update); $delete = trim($delete);
		if($table) $pname = $table;
		if(!$links)  $links = "table_page_links";
	
		$this->_CC_['delete'] = "";
		$update = trim($update);
		$delete = trim($delete);
		$where  = trim($where);
		$order  = trim($order);
		if(!$delete) $delete = "udf_079";
		if(!$update) $update = "udf_080";

		$this->_CC_['header'] = $pname;
		$flag = 0;
		if($this->username==$_SESSION['UserName'] && $this->cwd == $_SESSION['CWD']) $flag++;

		if(!$this->_CC_['max'])  $this->_CC_['max'] = 5;
		elseif($this->_CC_['max']>100)  $this->_CC_['max'] = 100;
		
		if($this->_CC_['author'])
		{
			if($where) $where .= " AND ";
			else $where .= "WHERE ";
			$this->_CC_['author'] = trim($this->_CC_['author']);
			$where .= "Author LIKE '".$this->_CC_['author']."%'";
		}
		if($this->_CC_['desc'])
		{
			if($where) $where .= " AND ";
			else $where .= "WHERE ";
			$where .= "Desc LIKE '%".$this->_CC_['desc']."%'";
		}
		if($this->_CC_['design'])
		{
			if($where) $where .= " AND ";
			else $where .= "WHERE ";
			$where .= "Design LIKE '%".$this->_CC_['design']."%'";
		}

		$q = @$this->DESIGNS->query("SELECT COUNT(*) FROM $pname $where");
		if($q===FALSE)
		{
			$this->_CC_['last'] = $this->_CC_['pnum'] = "0";
			$this->_CC_['content']  = $this->subString($header);
			$this->_CC_['content'] .= $this->subString($footer);
			if($flag) $this->_CC_['content'] .= $this->subString($form);
			return;
		}
		list($this->_CC_['NumItems']) = $q->fetch();
	
		if(!$this->_CC_['pnum']) $this->_CC_['pnum'] = 0;
		$rnum = $this->_CC_['pnum']*$this->_CC_['max'];
		if($rnum>=$this->_CC_['NumItems']) $rnum = $this->_CC_['NumItems']-$this->_CC_['max'];

		$this->_CC_['prev'] = $this->_CC_['pnum']-1;
		$this->_CC_['next'] = $this->_CC_['pnum']+1;
		$this->_CC_['last'] = (int)($this->_CC_['NumItems']/$this->_CC_['max']);
		if($this->_CC_['next']*$this->_CC_['max']>=$this->_CC_['NumItems'])
		{
			$this->_CC_['prev'] = $this->_CC_['next']-3;
			$this->_CC_['next'] = 0;
		}
		if($this->_CC_['prev']<0) $this->_CC_['prev'] = 0;

		$this->opMessage($links); // set page links

		if(!$order) $order = "ORDER BY mdate DESC";

		$q = $this->DESIGNS->query("SELECT * FROM $pname $where $order LIMIT $rnum,".$this->_CC_['max']);

		while( $q->valid() )
		{
			list($this->_CC_['ID'],$this->_CC_['design'],$this->_CC_['author'],$this->_CC_['did'],$this->_CC_['desc'],
			     $theme,$this->_CC_['downloads'],$this->_CC_['mdate']) = $q->current();
			
			$q->next();
			
			$rnum++ ;
			if($flag)
			{
				$this->_CC_['delete'] = $this->getUdfMsg($delete); // Delete this item
				$this->_CC_['update'] = $this->getUdfMsg($update); // Update this item
			}
			$this->_CC_['theme'] = "";
			if($_SESSION['UserName'])
			{
				if(file_exists("../templates/".$this->_CC_['design'].".tpl")) $theme = $this->_CC_['design'];
				elseif(file_exists("../templates/".$this->_CC_['author']."/".$this->_CC_['design'].".tpl"))
						$theme = $this->_CC_['author'].".".$this->_CC_['design'];
				if($theme) $this->_CC_['theme'] = "<a href='?set_theme=$theme'>Use This Theme</a>";
			}
			$this->_CC_['content'] .= $this->subString($fmt)."\n";
		}
		$this->_CC_['rnum'] = $rnum;
		$header = $this->subString($header);
		$this->_CC_['content'] .= $this->subString($footer);
		if($flag) $this->_CC_['content'] .= $this->subString($form);
		$this->_CC_['content'] = $header.$this->_CC_['content'];
	}

	/*-------------\
        | update table |
        \-------------*/
	function updateTable()
	{
		$table = $this->_CC_['table'];
		if(!$table) $table = $this->_CC_['d_table'];
		if(!$table) $table = $this->_CC_['page'];
		if(!$table)
		{
			echo "Must specifiy the name of the table.";
			exit;
		}
		if($_REQUEST['download'])
		{
			list($table,$author,$design) = explode(".",$_REQUEST['download']);
			$q = $this->DESIGNS->query("SELECT id,Downloads FROM $table WHERE Author='$author' AND Design='$design'");
			if($q===FALSE) return;

			list($id,$dls) = $q->fetch();
			$dls++ ;
			@$this->DESIGNS->query("UPDATE $table SET Downloads='$dls' WHERE id ='$id'");
			return;
		}
		if($this->_CC_['delete'])
		{
			$idnum = $this->_CC_['delete'];
			$q = $this->DESIGNS->query("SELECT id FROM $table WHERE id ='$idnum'");
			list($id) = $q->fetch();
			if(!$id)
			{
				echo "Record $idnum not in table $table!";
			}
			else
			{
				$q = $this->DESIGNS->query("DELETE FROM $table WHERE id ='$idnum'");
				echo "Record $id deleted from table $table!";
			}
			$this->opMessage("close_lytebox");
			exit;
		}
		$this->_CC_['desc'] = stripslashes($this->_CC_['desc']);
		if($this->_CC_['edit'])
		{
			$idnum = $this->_CC_['edit'];
			$q = $this->DESIGNS->query("SELECT * FROM $table WHERE id ='$idnum'");
			list($this->_CC_['id'], $this->_CC_['design'], $this->_CC_['author'],
			     $this->_CC_['did'], $this->_CC_['desc'], $this->_CC_['theme'],
			     $this->_CC_['downloads'], $this->_CC_['mdate']) = $q->fetch();

			$this->_CC_['design'] = stripslashes($this->_CC_['design']);
			$this->_CC_['author'] = stripslashes($this->_CC_['author']);
			$this->_CC_['desc']   = stripslashes($this->_CC_['desc']);

			$this->opForm($this->_CC_['form']);
			exit;
		}
		if($_POST['utype']=="update")
		{
			$id     = $_POST['id'];
			$did    = $_POST['did'];

			//$mdate  = $this->_CC_['datetime'];
			$author = sqlite_escape_string(stripslashes($_POST['author']));
			$design = sqlite_escape_string(stripslashes($_POST['design']));
			$desc   = sqlite_escape_string(stripslashes($_POST['desc']));
			$mdate  = sqlite_escape_string(stripslashes($_POST['mdate']));
			$design = preg_replace("/'/","_",$design);

			$q = $this->DESIGNS->query("UPDATE $table SET Author='$author',Design='$design',Desc='$desc',DID='$did',mdate='$mdate' WHERE id ='$id'");
			echo "Record $id in table $table updated!";
			
			$this->opMessage("close_lytebox");
			exit;
		}
		$this->addWdnDesign($table,$_REQUEST['design'],$_REQUEST['author'],$_REQUEST['id'],$_REQUEST['desc'],$_REQUEST['mdate']);
		$this->opMessage("close_lytebox");
		
		exit;
	}

        /*---------------\
        | add WDN design |
        \---------------*/
	function addWdnDesign($table,$design,$author,$id,$desc,$mdate)
	{
		if(!$author || !$design)
		{
			echo "Missing required info...";
			exit;
		}
		$des = sqlite_escape_string($design);
		$aut = sqlite_escape_string($author);
		$q = @$this->DESIGNS->query("SELECT id,Design,Author FROM $table WHERE Author='$aut' AND Design='$des'");
		if ($q === false)
		{
			$this->createDbase("design",$table);
			echo "Table ($table) created<br />";
		}
		else
		{
			list($tid,$des,$aut) = $q->fetch();
			if($author==$aut && $design==$des)
			{
				echo "<font color='red'>$des by $author was already addeded ($tid)</font><br />";
				return 1;
			}
		}

		$design = sqlite_escape_string($design);
		$author = sqlite_escape_string($author);
		$desc   = sqlite_escape_string($desc);
		if($table != "urls")
		{
			$design = preg_replace("/([\.| ])/","_",$design);
			$author = preg_replace("/([\.| ])/","_",$author);
			$mdate = substr($this->_CC_['datetime'],0,8);
			$mdate = sprintf("%s%04d",$mdate,$id);
		}
		else	$mdate = $this->_CC_['datetime'];
		
		$q = $this->DESIGNS->query("INSERT INTO $table VALUES(NULL, '$design', '$author', '$id', ".
					       "'$desc', 'NULL', '0', '$mdate')");

		echo "<font color='green'>ID $id addeded ($design, $author)</font><br />";

		$site = "";
		if(!$_SESSION['usite'])
		{
			preg_match("/.*([\\\|\/])([a-zA-Z0-9_]+)\/([a-zA-Z0-9_]+)$/", getcwd(), $dirs);
			$site = "/$dirs[2]";
		}
		if($_REQUEST['odcms_googlecode'])
		{
			echo @file_get_contents("http://".$_SERVER["SERVER_NAME"]."$site/codes/archive.php?odcms_googlecode=$author".
						"_$design");
			return;
		}
		if($_FILES["zipfile"]["tmp_name"])
		{
			$data = @file_get_contents($_FILES["zipfile"]["tmp_name"]);
		}
		elseif($this->_CC_['url'])
		{
			$data = @file_get_contents($this->_CC_['url']);
		}
		if($data)
		{
			$fp = fopen("../designs/$author/$design.zip","w");
			fwrite($fp,$data);
			fclose($fp);
			echo "http://".$_SERVER["SERVER_NAME"]."$site/codes/archive.php?design=$author.$design";
			echo @file_get_contents("http://".$_SERVER["SERVER_NAME"]."$site/codes/archive.php?design=$author.$design");
		}
		if($table == "urls")
		{
			$this->_CC_['page'] = "?Page=".$this->_CC_['Page'];
			$this->opMessage("reload_page");
			exit;
		}
		return 0;
	}
	
        /*----------------\
        | download design |
        \----------------*/
	function downloadDesign($design)
	{
		$table = $this->_CC_['table'];
		if(!$table) $table = $this->_CC_['d_table'];
		if(!$table) $table = $this->_CC_['page'];
		if(!$table)
		{
			echo "Must specifiy the name of the table.";
			exit;
		}
		$this->DESIGNS = new SQLiteDatabase("./designs.dbf"); // my designs database
		$q = $this->DESIGNS->query("SELECT id,Downloads FROM $table WHERE Design='$design'");
		if(!$q)
		{
			$this->_CC_['Page'] = "_CC_";
			$this->_CC_['content'] = "<h3>Error in opening database</h3>";
			return;
		}
		list($id,$dls) = $q->fetch();
		if(!$id)
		{
			$this->_CC_['Page'] = "_CC_";
			$this->_CC_['content'] = "<h3>Design ($design) not found</h3>";
			return;
		}
		$dls++ ;
		@$this->DESIGNS->query("UPDATE $table SET Downloads='$dls' WHERE id ='$id'");

		$file = "../designs/$table/$design.zip";
		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		header("Content-Disposition: attachment; filename=$design.zip");
		header('Content-Transfer-Encoding: binary');
		header('Content-Length: ' . filesize($file));
		
		ob_clean();
		flush();
		readfile($file);

		exit;
	}

	/*------------------\
        | get local content |
        \------------------*/
	function showLocalContent($pname)
	{
		if($pname == "Contact Us") return $this->pageContactUs();
		if($pname == "Term of Use") return $this->pageTOU();
		
		$this->_CC_['content'] = "Page <i>$pname</i> is under construction!";
	}

        /*------------\
        | term of use |
        \------------*/
	function pageTOU()
	{
		$this->_CC_['content'] =  @file_get_contents("./termofuse.html");
	}
	
        /*-----------\
        | contact us |
        \-----------*/
	function pageContactUs()
	{
		$this->_CC_['REMOTE'] = $_SERVER['REMOTE_ADDR'];
		$this->_CC_['vfy'] = "";
	
		if(!$_POST['FROM'] || !$_POST['EMAIL'] || !$_POST['SUBJECT'] || !$_POST['MESSAGE'])
		{
			$this->_CC_['vfy'] = 1;
		}
	        elseif($this->checkVerification()) $this->_CC_['vfy'] = 2;
		
		if( $this->_CC_['vfy'] == 1 )
		{
			if($_POST['TO']) $this->_CC_['wrong_code'] = $this->getUdfMsg("udf_065"); // Missing required info
		}
	        else if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST['EMAIL']))
		{
			if(!$_GET['TO']) $this->_CC_['wrong_code'] = $this->getUdfMsg("udf_086"); // Invalid email;
		}
	        else if($this->_CC_['vfy'] == 2 && !$_SESSION['UserName'])
		{
			$this->_CC_['wrong_code'] = $this->getUdfMsg("udf_066"); // Wrong verification code
		}
	        else
		{
			if( !file_exists("./users/$this->username/mail.dbf") )
			{
				$this->MAIL = new SQLiteDatabase("./users/$this->username/mail.dbf"); // user mail database
				$this->createDbase("mail","mail");
			}
			else $this->MAIL = new SQLiteDatabase("./users/$this->username/mail.dbf"); // mail database

			$uname = $_POST['FROM'];
			$email = $_POST['EMAIL'];
			$subject = sqlite_escape_string($_POST['SUBJECT']);
			$message = sqlite_escape_string($_POST['MESSAGE']);
			$q = $this->MAIL->query("INSERT INTO mail VALUES(NULL,'$uname','".
					$this->_CC_['datetime']."','$email','".$this->_CC_['REMOTE'].
					"','$subject','$message')");
			if ($q === false)
			{
				echo "Error adding mail message";
				exit;
			}
			$this->_CC_['content'] =  "<h3>Your message is successfully sent!</h3>";
			
			mail($this->_CC_['email'], "You have received a message from ".
			     $_POST['FROM'] , "Subject: ".$_POST['SUBJECT'], "From: ".$this->_CC_['WEBSITE']." Network\n");
					
			return;
		}

		$this->_CC_['content'] = $this->getTplMsg("contact_us");

		return;
	}
	
	/*------------------------\
        | check verification code |
        \------------------------*/
	function checkVerification()
	{
		$verif_box = $_POST['verif_box'];
		// check to see if verificaton code was correct
		$num = md5($verif_box).'a4xn';
		$cok = $_SESSION['rand_number'];
		if($num == $cok)
		{
			// delete the cookie so it cannot sent again by refreshing this page
			$_SESSION['rand_number'] = "";
			return 0;
		}
		return 1;
	}
	
        /*---------------\
        | local database |
        \---------------*/
	function localDbase()
	{
		$this->DESIGNS = new SQLiteDatabase("./designs.dbf"); // WDN designs database
	}
	
        /*----------------------\
        | create database table |
        \----------------------*/
	function createDesignDbase($table)
	{
		$this->DESIGNS->query("CREATE TABLE $table".
				      " ( id INTEGER PRIMARY KEY, Design CHAR(80), Author CHAR(80), DID INTEGER, ".
				      "Desc TEXT, Theme CHAR(80), Downloads INTEGER, mdate INTEGER)");
	}

        /*--------------\
        | update points |
        \--------------*/
	function updatePoints()
	{
		echo "updatePoints function is deleted!";
		exit;
	}
	
        /*--------------\
        | delete member |
        \--------------*/
	function deleteMember($mname)
	{
		if($_SESSION['UserName'] != "admin") return;
		
		$this->removeDirectory("../_$mname");
		
		$this->MEMBERS->query("DELETE FROM members WHERE ID='$mname'");
		$this->MEMBERS->query("DELETE FROM activities WHERE UID='$mname'");
		
		$this->_CC_['page'] = "?Page=_members_";
		$this->opMessage("reload_page");
		exit;
	}
	
        /*-----------------\
        | remove directory |
        \-----------------*/
	function removeDirectory($dir)
	{
		$this->_CC_['status'] =  "";
		$handle = @opendir($dir);
		if(!$handle)
		{
			$this->_CC_['status'] .= "<font color='red'>Unable to open $dir.</font><br /><br />";
			return;
		}
		while (false !== ($file = readdir($handle)))
		{
			if($file[0] == ".") continue;
			if(is_dir("$dir/$file")) $this->removeDirectory("$dir/$file");
			else
			{
				if(@unlink("./$dir/$file")) $this->_CC_['status'] .= "$dir/$file deleted.<br />";
			else $this->_CC_['status'] .= "<font color='red'>Error encountered deleting $dir/$file.</font><br />";
			}
		}
		if(@rmdir($dir)) $this->_CC_['status'] .= "Directory $dir/$file deleted.<br /><br />";
		else $this->_CC_['status'] .= "<font color='red'>Error encountered deleting directory $dir.</font><br /><br />";
	}

}
?>
